package sms_kuailian

import (
	"context"
	"fmt"
)

type SMS struct {
	cli *Client
}

func MustNew(cfgPath string) *SMS {
	cfg, err := LoadFrom(cfgPath)
	if err != nil {
		panic(err)
	}
	return &SMS{cli: New(cfg)}
}

// ---------- 对外友好接口 ----------

// 单条验证码
func (s *SMS) SendCode(ctx context.Context, phone, code string) (uid string, err error) {
	msg := fmt.Sprintf("【陕西向途教育】验证码：%s，5分钟内有效，请勿告诉他人。", code)
	req := &SendReq{Phone: phone, Msg: msg}
	rsp, err := s.cli.Send(ctx, req)
	if err != nil {
		return "", err
	}
	return rsp.UID, nil
}

// 批量营销
func (s *SMS) SendBatch(ctx context.Context, phones []string, content string) (uid string, err error) {
	// 简单拼逗号，生产环境请校验号码
	req := &SendReq{
		Phone: join(phones),
		Msg:   content,
	}
	rsp, err := s.cli.Send(ctx, req)
	if err != nil {
		return "", err
	}
	return rsp.UID, nil
}

// 查余额
func (s *SMS) Balance(ctx context.Context) (int64, error) {
	rsp, err := s.cli.Balance(ctx)
	if err != nil {
		return 0, err
	}
	var b int64
	fmt.Sscanf(rsp.Balance, "%d", &b)
	return b, nil
}

func join(p []string) string {
	// 生产可用 strings.Join
	if len(p) == 0 {
		return ""
	}
	return p[0]
}
